package favorite.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import favorite.mapper.FavoriteMapper;
import favorite.service.IFavoriteService;
import favorite.service.GoodsServiceFeignClient;
import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import common.model.user.Favorite;
import common.dto.userdto.FavoriteDTO;
import common.dto.goodsdto.SpuVO;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FavoriteServiceImpl implements IFavoriteService {
    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GoodsServiceFeignClient goodsServiceFeignClient;

    @Autowired
    private ObjectMapper objectMapper;

    //获取用户收藏列表
    @Override
    public Result findListByUid(Long userId) {
        // 查询用户的收藏列表
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                   .eq(Favorite::getIsDeleted, 0);
        List<Favorite> favoriteList = favoriteMapper.selectList(queryWrapper);
        
        // 将收藏列表转换为 FavoriteDTO 列表
        List<FavoriteDTO> favoriteDTOList = favoriteList.stream().map(favorite -> {
            FavoriteDTO favoriteDTO = new FavoriteDTO();
            favoriteDTO.setId(favorite.getId());
            favoriteDTO.setUserId(favorite.getUserId());
            favoriteDTO.setSpuId(favorite.getSpuId());
            favoriteDTO.setIsDeleted(favorite.getIsDeleted());
            
            // 调用商品服务获取 SpuVO 信息
            Result spuResult = goodsServiceFeignClient.getSpuById(favorite.getSpuId().longValue());
            if (spuResult.getCode() == 200) {
                try {
                    // 使用 ObjectMapper 进行类型转换
                    SpuVO spuVO = objectMapper.convertValue(spuResult.getData(), SpuVO.class);
                    favoriteDTO.setSpuVO(spuVO);
                } catch (Exception e) {
                    // 如果转换失败，记录错误并继续处理
                    System.err.println("转换 SpuVO 失败: " + e.getMessage());
                }
            }
            
            return favoriteDTO;
        }).collect(Collectors.toList());
        
        return Result.success(favoriteDTOList);
    }

    //判断当前商品是否已经收藏
    public Result isFavorite(Long userId, Long spuId) {
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                   .eq(Favorite::getSpuId, spuId);
        Favorite favorite = favoriteMapper.selectOne(queryWrapper);
        
        // 如果查询结果为空，返回成功（未收藏）
        if (favorite == null) {
            return Result.success();
        }
        
        // 如果软删除标记为1，返回成功（未收藏）
        if (favorite.getIsDeleted() == 1) {
            return Result.success();
        }
        
        // 如果软删除标记为0，返回收藏记录（已收藏）
        return Result.success(favorite);
    }

    //添加收藏
    @Override
    public Result addFavorite(Long userId, Long spuId) {
        // 首先检查是否存在未删除的收藏记录
        LambdaQueryWrapper<Favorite> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(Favorite::getUserId, userId)
                   .eq(Favorite::getSpuId, spuId)
                   .eq(Favorite::getIsDeleted, 0);
        
        Favorite existingActiveFavorite = favoriteMapper.selectOne(checkWrapper);
        if (existingActiveFavorite != null) {
            return Result.success("该商品已经收藏");
        }

        // 查询是否存在软删除的收藏记录
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                   .eq(Favorite::getSpuId, spuId)
                   .eq(Favorite::getIsDeleted, 1);
        
        Favorite existingFavorite = favoriteMapper.selectOne(queryWrapper);
        
        if (existingFavorite != null) {
            // 如果存在软删除的记录，则恢复它
            LambdaUpdateWrapper<Favorite> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Favorite::getId, existingFavorite.getId())
                        .set(Favorite::getIsDeleted, 0)
                        .set(Favorite::getUpdateTime, LocalDateTime.now());
            
            favoriteMapper.update(null, updateWrapper);
            return Result.success("收藏恢复成功");
        } else {
            // 如果不存在，创建新的收藏记录
            Favorite favorite = new Favorite();
            favorite.setUserId(userId);
            favorite.setSpuId(spuId.intValue());
            favorite.setIsDeleted(0);
            favorite.setCreateTime(LocalDateTime.now());
            favorite.setUpdateTime(LocalDateTime.now());
            
            favoriteMapper.insert(favorite);
            return Result.success("收藏添加成功");
        }
    }

    //取消收藏
    @Override
    public Result cancelFavorite(Long userId, Long spuId) {
        // 构建更新条件
        LambdaUpdateWrapper<Favorite> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Favorite::getUserId, userId)
                    .eq(Favorite::getSpuId, spuId)
                    .eq(Favorite::getIsDeleted, 0)
                    .set(Favorite::getIsDeleted, 1)
                    .set(Favorite::getUpdateTime, LocalDateTime.now());
        
        // 执行更新
        int result = favoriteMapper.update(null, updateWrapper);
        
        if (result > 0) {
            return Result.success("取消收藏成功");
        } else {
            return Result.failure(ResultCodeEnum.FAIL, "取消收藏失败，可能该商品未被收藏");
        }
    }
    // //检查此页商品是否有用户收藏
    // @Override
    // public Result findGoodsIsFavorite(Long uid, List<Long> spuIds, Integer page) {
    //     //1.查询redis缓存中是否有此用户在此页商品列表收藏判断缓存，有则直接返回缓存数据，没有则继续
    //     //2.查询数据库中用户收藏列表，和此页商品id进行匹配，匹配成功则说明有收藏，其他则无
    //     //3.将匹配成功的商品的isfavorite设为1，其他设为0，然后保存到List<GoodsIsFavorite>中，然后存入GoodsFavoriteDTO中
    //     //4.建立缓存
    //     //5.返回缓存信息
    //     return Result.success(goodsFavoriteDTO)
    // }
}
